package com.sunfeng.chap2;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * @Description: 在使用 long transferTo(long position, long count,WritableByteChannel target) 方法时 注意一下两种情况
 * 1） 如果count 的字节个数大于position到size的字节个数，则传输size-position个字节数到dest通道的当前位置
 * 2） 如果count的字节个数小于或者等于position 到size的字节个数，则传输count个字节数到dest通道的当前位置
 * <p>
 * 113a.txt 文件默认内容如下: 1234567890
 */
public class Test11_3 {
    public static void main(String[] args) throws IOException {

        test2();
    }

    /**
     *  验证第一种情况
     * @throws IOException
     */
    private static void test1() throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile("d:\\nio\\113a.txt", "rw");
        RandomAccessFile randomAccessFile2 = new RandomAccessFile("d:\\nio\\113b.txt", "rw");
        FileChannel fileChannel1 = randomAccessFile.getChannel();
        FileChannel fileChannel2 = randomAccessFile2.getChannel();

        System.out.println("A posotion=" + fileChannel2.position() + " size=" + fileChannel2.size());
        fileChannel1.transferTo(0, 1000, fileChannel2);
        System.out.println("b posotion=" + fileChannel2.position() + " size=" + fileChannel2.size());
        fileChannel1.close();
        fileChannel2.close();
        randomAccessFile2.close();
        randomAccessFile.close();
    }

    /**
     * 验证第二种情况  23456
     * @throws IOException
     */
    private static void test2() throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile("d:\\nio\\113a.txt", "rw");
        RandomAccessFile randomAccessFile2 = new RandomAccessFile("d:\\nio\\113b.txt", "rw");
        FileChannel fileChannel1 = randomAccessFile.getChannel();
        FileChannel fileChannel2 = randomAccessFile2.getChannel();

        System.out.println("A posotion=" + fileChannel2.position() + " size=" + fileChannel2.size());
        fileChannel1.transferTo(1, 5, fileChannel2);
        System.out.println("b posotion=" + fileChannel2.position() + " size=" + fileChannel2.size());
        fileChannel1.close();
        fileChannel2.close();
        randomAccessFile2.close();
        randomAccessFile.close();
    }
}
